package org.android.pasos;

import org.android.pasos.activities.firstview.AssistanceActivity;
import org.android.pasos.activities.firstview.ConfigActivity;
import org.android.pasos.activities.firstview.EmergencyActivity;
import org.android.pasos.data.PasosApplication;
import org.android.pasos.util.InicializacionTask;
import org.android.pasos.util.UtilJSON;
import org.android.pasos.util.UtilTrama;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.view.accessibility.AccessibilityManager;

public class MainActivity extends Activity implements OnInitListener {
	/** Called when the activity is first created. */
	private Vibrator vibrator;
	private TextToSpeech tts;
	public SharedPreferences mPrefs;
	private AccessibilityManager accessibilityManager;
	BroadcastReceiver batteryReceiver;
	public ProgressDialog progressDialog;

	// Intent intent = null;

	// private Hablar voz;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mPrefs = getSharedPreferences("PasosPreferences", MODE_PRIVATE);

		// Sirve para obligar a que se retomen los datos del servidor
//		mPrefs.edit().remove("Ugrupo").commit();

		PasosApplication appState = ((PasosApplication) getApplicationContext());

		if (!appState.isInicializado()) {
			InicializacionTask task = new InicializacionTask(this);
			task.execute();
		}

		Context ctx = getApplicationContext();
		Resources res = ctx.getResources();

		// voz = new Hablar();
		tts = new TextToSpeech(this, this);
		accessibilityManager = (AccessibilityManager) ctx
				.getSystemService(Context.ACCESSIBILITY_SERVICE);

		String[] options = res.getStringArray(R.array.title_names);
		TypedArray icons = res.obtainTypedArray(R.array.pasos_icons);

		// setListAdapter(new ImageAndTextAdapter(ctx, R.layout.main_list_item,
		// options, icons));

		new Thread() {
			public void run() {
				// Control Battery low
				batteryReceiver = new BroadcastReceiver() {
					@Override
					public void onReceive(Context context, Intent intent) {
						// Se envia la peticion REST al servidor
						DatosTrama dt = UtilTrama
								.creartrama(getApplicationContext());
						UtilJSON.enviarIncidencia(getApplicationContext(),
								Constants.URL_INCIDENCIAS_REST,
								Constants.BATERIA_BAJA, dt);
					}
				};

				registerReceiver(batteryReceiver, new IntentFilter(
						Intent.ACTION_BATTERY_LOW));
			}
		}.start();
	}

	public void onEmergency(View view) {
		hablar(this.getString(R.string.tts_emergencia));
		// Option --> EMERGENCY
		// Hace que vibre al pulsar
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(50);

		Intent intent = new Intent(MainActivity.this, EmergencyActivity.class);
		startActivity(intent);

	}

	public void onAssistance(View view) {
		hablar(this.getString(R.string.tts_asistencia));
		// Option --> ASSISTANCE
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(50);

		Intent intent = new Intent(MainActivity.this, AssistanceActivity.class);
		startActivity(intent);
	}

	public void onWalk(View view) {
		hablar(this.getString(R.string.tts_paseo));
		// Option --> WALK
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(50);

		Intent intent = new Intent(MainActivity.this, WalkMainActivity.class);
		startActivity(intent);
	}

	public void onConfig(View view) {
		hablar(this.getString(R.string.tts_configurar));
		// Option --> CONFIGURATION
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(50);

		Intent intent = new Intent(MainActivity.this, ConfigActivity.class);
		startActivity(intent);

	}

	/**
	 * public void onListItemClick(ListView parent, View v, int position, long
	 * id) { Intent intent = null; // Show position clicked /**
	 * Toast.makeText(getApplicationContext(), "You have selected " + (position
	 * + 1) + "th item", Toast.LENGTH_SHORT).show();
	 */
	/**
	 * switch (position) { case 0: hablar("emergencia"); // Option --> EMERGENCY
	 * // Hace que vibre al pulsar vibrator = (Vibrator)
	 * getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(50);
	 * 
	 * intent = new Intent(MainActivity.this, EmergencyActivity.class);
	 * startActivity(intent); break;
	 * 
	 * case 1: hablar("asistencia"); // Option --> ASSISTANCE vibrator =
	 * (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	 * vibrator.vibrate(50);
	 * 
	 * intent = new Intent(MainActivity.this, AssistanceActivity.class);
	 * startActivity(intent); break; case 2: hablar("paseo"); // Option --> WALK
	 * vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	 * vibrator.vibrate(50);
	 * 
	 * intent = new Intent(MainActivity.this, WalkMainActivity.class);
	 * startActivity(intent); break;
	 * 
	 * case 3: hablar("consulta"); // Option --> CONSULTATION vibrator =
	 * (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	 * vibrator.vibrate(50);
	 * 
	 * intent = new Intent(MainActivity.this, ConsultActivity.class);
	 * startActivity(intent); break; case 4: hablar("configurar"); // Option -->
	 * CONFIGURATION vibrator = (Vibrator)
	 * getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(50);
	 * 
	 * intent = new Intent(MainActivity.this, ConfigActivity.class);
	 * startActivity(intent); break; }
	 * 
	 * }
	 */

	private void hablar(String mensaje) {
		if (accessibilityManager.isEnabled()) {
			tts.speak(mensaje, TextToSpeech.QUEUE_FLUSH, null);
		}
	}

	public void onInit(int status) {
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		tts.shutdown();
		if (batteryReceiver.isOrderedBroadcast()) {
			unregisterReceiver(batteryReceiver);
		}
		super.onDestroy();
	}
}
